import { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { useTheme } from '@/hooks/useTheme';
import { cn } from '@/lib/utils';

// 模拟商品数据
interface Product {
  id: string;
  title: string;
  price: number;
  originalPrice?: number;
  image: string;
  category: string;
  location: string;
  postedAt: string;
}

const mockProducts: Product[] = [
  {
    id: '1',
    title: '九成新 MacBook Pro 2023',
    price: 8999,
    originalPrice: 11999,
    image: 'https://space.coze.cn/api/coze_space/gen_image?image_size=square&prompt=laptop%20macbook%20pro%20new%20condition&sign=20f4f73de7dc224e47978f4a391ca9b9',
    category: '电子产品',
    location: '主校区',
    postedAt: '2小时前'
  },
  {
    id: '2',
    title: '大学英语四级词汇书',
    price: 25,
    originalPrice: 45,
    image: 'https://space.coze.cn/api/coze_space/gen_image?image_size=square&prompt=english%20vocabulary%20book%20for%20exam&sign=69084fa9b4b4f62bc00931f403d1340b',
    category: '书籍资料',
    location: '东校区',
    postedAt: '5小时前'
  },
  {
    id: '3',
    title: '专业相机 Canon EOS R5',
    price: 13500,
    originalPrice: 18999,
    image: 'https://space.coze.cn/api/coze_space/gen_image?image_size=square&prompt=canon%20camera%20eos%20r5%20professional%20photography&sign=30344d19f8696fe1cf5b3eea840ba9d2',
    category: '电子产品',
    location: '南校区',
    postedAt: '昨天'
  },
  {
    id: '4',
    title: '篮球装备套装',
    price: 199,
    originalPrice: 350,
    image: 'https://space.coze.cn/api/coze_space/gen_image?image_size=square&prompt=basketball%20equipment%20set%20with%20ball%20and%20shoes&sign=c7c0864626ca8ad7c63c6063a27ea339',
    category: '运动器材',
    location: '主校区',
    postedAt: '3天前'
  },
  {
    id: '5',
    title: '考研政治复习资料全套',
    price: 120,
    originalPrice: 260,
    image: 'https://space.coze.cn/api/coze_space/gen_image?image_size=square&prompt=postgraduate%20entrance%20exam%20political%20study%20materials&sign=ff90125a8a72b3ed5135015226dc85fb',
    category: '书籍资料',
    location: '西校区',
    postedAt: '1周前'
  },
  {
    id: '6',
    title: '小型咖啡机',
    price: 350,
    originalPrice: 699,
    image: 'https://space.coze.cn/api/coze_space/gen_image?image_size=square&prompt=small%20coffee%20machine%20home%20use&sign=f9436bb7c5cb7a23be2dbc7c6ed4c01d',
    category: '家居用品',
    location: '主校区',
    postedAt: '2周前'
  }
];

// 分类数据
const categories = [
  { id: 'all', name: '全部', icon: 'fa-th-large' },
  { id: 'electronics', name: '电子产品', icon: 'fa-laptop' },
  { id: 'books', name: '书籍资料', icon: 'fa-book' },
  { id: 'sports', name: '运动器材', icon: 'fa-futbol' },
  { id: 'home', name: '家居用品', icon: 'fa-home' },
  { id: 'fashion', name: '服饰鞋包', icon: 'fa-tshirt' }
];

export default function Home() {
  const [products, setProducts] = useState<Product[]>(mockProducts);
  const [selectedCategory, setSelectedCategory] = useState('all');
  const [searchQuery, setSearchQuery] = useState('');
  const { theme, toggleTheme } = useTheme();

  // 筛选商品
  useEffect(() => {
    let filtered = [...mockProducts];
    
    // 按分类筛选
    if (selectedCategory !== 'all') {
      const categoryMap: Record<string, string> = {
        'electronics': '电子产品',
        'books': '书籍资料',
        'sports': '运动器材',
        'home': '家居用品',
        'fashion': '服饰鞋包'
      };
      
      filtered = filtered.filter(p => p.category === categoryMap[selectedCategory]);
    }
    
    // 按搜索关键词筛选
    if (searchQuery) {
      const query = searchQuery.toLowerCase();
      filtered = filtered.filter(p => 
        p.title.toLowerCase().includes(query) || 
        p.category.toLowerCase().includes(query)
      );
    }
    
    setProducts(filtered);
  }, [selectedCategory, searchQuery]);

  return (
    <div className={cn("min-h-screen bg-gray-50 dark:bg-gray-900")}>
      {/* 搜索栏 */}
      <div className="sticky top-0 z-10 bg-white dark:bg-gray-800 shadow-sm px-4 py-3">
        <div className="max-w-6xl mx-auto flex flex-col md:flex-row gap-3 items-center justify-between">
          <div className="flex items-center gap-2 w-full md:w-auto">
            <h1 className="text-2xl font-bold text-indigo-600 dark:text-indigo-400">校园二手</h1>
            <button 
              onClick={toggleTheme}
              className="p-2 rounded-full hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
            >
              <i className={`fa-solid ${theme === 'light' ? 'fa-moon' : 'fa-sun'} text-gray-600 dark:text-gray-300`}></i>
            </button>
          </div>
          
          <div className="relative w-full md:w-96">
            <input
              type="text"
              placeholder="搜索商品..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="w-full py-2 px-4 pr-10 rounded-full border border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-900 focus:outline-none focus:ring-2 focus:ring-indigo-500"
            />
            <i className="fa-solid fa-search absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
          </div>
        </div>
      </div>
      
      {/* 分类导航 */}
      <div className="overflow-x-auto bg-white dark:bg-gray-800 shadow-sm px-4 py-2 sticky top-[76px] z-10">
        <div className="max-w-6xl mx-auto flex gap-4 min-w-max">
          {categories.map((category) => (
            <button
              key={category.id}
              onClick={() => setSelectedCategory(category.id)}
              className={`flex items-center gap-2 px-4 py-2 rounded-full transition-all ${
                selectedCategory === category.id
                  ? 'bg-indigo-100 dark:bg-indigo-900 text-indigo-600 dark:text-indigo-400 font-medium'
                  : 'hover:bg-gray-100 dark:hover:bg-gray-700 text-gray-600 dark:text-gray-300'
              }`}
            >
              <i className={`fa-solid ${category.icon}`}></i>
              <span>{category.name}</span>
            </button>
          ))}
        </div>
      </div>
      
      {/* 商品列表 */}
      <div className="max-w-6xl mx-auto px-4 py-8">
        <h2 className="text-xl font-bold mb-6 text-gray-800 dark:text-gray-200">
          {selectedCategory === 'all' ? '全部商品' : categories.find(c => c.id === selectedCategory)?.name}
        </h2>
        
        {products.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-16 text-center">
            <i className="fa-solid fa-box-open text-6xl text-gray-300 dark:text-gray-600 mb-4"></i>
            <h3 className="text-xl font-medium text-gray-700 dark:text-gray-300">暂无商品</h3>
            <p className="text-gray-500 dark:text-gray-400 mt-2">
              没有找到符合条件的商品，请尝试其他分类或搜索关键词
            </p>
          </div>
        ) : (
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
            {products.map((product) => (
              <Link 
                key={product.id} 
                to={`/product/${product.id}`}
                className="group block bg-white dark:bg-gray-800 rounded-xl shadow-sm hover:shadow-md transition-all overflow-hidden"
              >
                <div className="relative h-48 overflow-hidden">
                  <img 
                    src={product.image} 
                    alt={product.title}
                    className="w-full h-full object-cover transform group-hover:scale-105 transition-transform duration-300"
                  />
                  <div className="absolute top-2 right-2 bg-red-500 text-white text-xs px-2 py-1 rounded">
                    {product.postedAt}
                  </div>
                </div>
                <div className="p-4">
                  <div className="flex items-start justify-between mb-2">
                    <h3 className="font-medium text-gray-800 dark:text-gray-200 line-clamp-2 h-12">
                      {product.title}
                    </h3>
                    <div className="flex flex-col items-end">
                      <span className="font-bold text-indigo-600 dark:text-indigo-400">¥{product.price}</span>
                      {product.originalPrice && (
                        <span className="text-xs text-gray-400 line-through">¥{product.originalPrice}</span>
                      )}
                    </div>
                  </div>
                  <div className="flex items-center justify-between text-sm text-gray-500 dark:text-gray-400">
                    <span className="flex items-center">
                      <i className="fa-solid fa-tag mr-1"></i>
                      {product.category}
                    </span>
                    <span className="flex items-center">
                      <i className="fa-solid fa-location-dot mr-1"></i>
                      {product.location}
                    </span>
                  </div>
                </div>
              </Link>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}